package algorithmForInterview40;

/**
 * @author 03010570
 * @date 2020/06/18
 * describe:    LeetCode:24、两两交换链表中的节点 https://leetcode-cn.com/problems/swap-nodes-in-pairs/
 */
public class LeetCode_24 {
    public static void main(String[] args) {
        final ListNode node = new ListNode(1);
        node.next = new ListNode(2);
        node.next.next = new ListNode(3);
        node.next.next.next = new ListNode(4);
        final LeetCode_24 code24 = new LeetCode_24();
        ListNode node1 = code24.swapPairs2(node);
        while (node1 != null) {
            System.out.print(node1.val + "—>");
            node1 = node1.next;
        }
    }

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode node = new ListNode(0);
        node.next = head;
        ListNode curr = node;
        while (curr.next != null && curr.next.next != null) {
            ListNode start = curr.next;
            ListNode end = curr.next.next;
            curr.next = end;          // 0 -> 2
            start.next = end.next;    // 1 -> 3
            end.next = start;         // 2 ->1
            curr = start;           // 当前节点 = 2
        }

        return node.next;
    }

    /**
     * 递归:
     *  1 -> 2.next
     *  2 - 1
     *
     * @param head
     * @return
     */
    public ListNode swapPairs2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode first = head;
        ListNode second = head.next;
        first.next = swapPairs2(second.next);
        second.next = first;
        return second;
    }
}
